package com.sd365.gateway.core.filter;

import com.sd365.gateway.core.config.CustomFilters;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author zhengjianjian
 * @version 1.0.0
 * @class MyTokenGatewayFilter
 * @classdesc 判断Token是否存在，转发到授权中心
 * @date 2020/12/18
 * @see
 * @since
 */
@Slf4j
@Component
public class MyTokenGatewayFilter implements GlobalFilter, Ordered {
    /**
     * 创建对象的时候包含了ribbon功能
     */
    @Resource
    private RestTemplate restTemplate;
    /**
     * nacos 配置文件中配置的客户指定放行的过滤器
     */
    @Autowired
    private CustomFilters customFilters;
    /**
     * 网关服务地址
     */
    public static final String AUTHORIZATION_URL = "http://gateway-authorization";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String URI = exchange.getRequest().getURI().toString();
        log.info("请求的url：{} this{}", URI, this);
        if (filterConstant(URI)) {
            //如果是登录请求， 就直接放行
            return chain.filter(exchange);
        } else {
            List<String> accessToken = exchange.getRequest().getHeaders().get("accessToken");
            if (!CollectionUtils.isEmpty(accessToken)) {
                //请求携带， 去做鉴权操作
                return doAuthorization(exchange, chain, accessToken, URI);
            } else {
                //请求没有token， 查询公共资源， 依情况返回结果
                return toCommonResource(URI, chain, exchange);
            }
        }
    }

    /***
     * @Description 查询公共资源， 如果访问的是公共资源就放行， 不是就返回
     * @Param No such property: code for class: Script1
     * @return reactor.core.publisher.Mono<java.lang.Void>
     * @Date 2022/12/18 16:51
     * @Author hantianbing
     **/
    Mono<Void> toCommonResource(String URI,GatewayFilterChain chain, ServerWebExchange exchange ){
        log.info("请求的url：{} this{},{}", URI, this,"无token去查询公共资源");
        Boolean canGet = null;
        try {
            //查看访问的是不是公共资源， 能不能成功
            canGet = restTemplate.getForObject(AUTHORIZATION_URL + "/v1/common/resource?&url=" + URI, Boolean.class);
        } catch (RestClientException e) {
            e.printStackTrace();
            exchange.getResponse().setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
            return exchange.getResponse().setComplete();
        }
        //如果可以访问就放行， 否则就直接返回
        if (canGet !=null && canGet) {
            log.info("请求的url：{} this{},{}", URI, this,"无token去查询公共资源成功");
            return chain.filter(exchange);
        } else {
            log.info("请求的url：{} this{},{}", URI, this,"无token去查询公共资源失败");
            exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
            return exchange.getResponse().setComplete();
        }
    }

    /***
     * @Description 做鉴权， 根据鉴定的结果判断能不能通过
     * @return reactor.core.publisher.Mono<java.lang.Void>
     * @Date 2022/12/18 16:33
     * @Author hantianbing
     **/
    Mono<Void> doAuthorization(ServerWebExchange exchange, GatewayFilterChain chain, List<String> accessToken, String URI){
        log.info("请求的url：{} this{},{}", URI, this,"带token去鉴权");
        //鉴权请求发送， 接收结果
        Boolean canGet = null;
        try {
            canGet = restTemplate.getForObject(AUTHORIZATION_URL + "/v1/authorization?token=" + accessToken.toString() + "&url=" + URI, Boolean.class);
        } catch (RestClientException e) {
            e.printStackTrace();
            exchange.getResponse().setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
            return exchange.getResponse().setComplete();
        }
        //如果鉴权成功， 放行， 不成功返回
        if (canGet!=null &&canGet) {
            log.info("请求的url：{} this{},{}", URI, this,"带token去鉴权成功");
            return chain.filter(exchange);
        } else {
            log.info("请求的url：{} this{},{}", URI, this,"带token去鉴权失败");
            exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
            return exchange.getResponse().setComplete();
        }
    }

    @Override
    public int getOrder() {
        return 2;
    }

    /***
     * @Description 判断有没有这个Url
     * @param URI 目标url
     * @return java.lang.Boolean
     * @Date 2022/12/29 16:14
     * @Author hantianbing
     **/
    private Boolean filterConstant(String URI) {
        if (!CollectionUtils.isEmpty(customFilters.getFilters())) {
            for (String filter : customFilters.getFilters()) {
                if (URI.contains(filter)) {
                    return true;
                }
            }
            return false;
        } else {
            return false;
        }
    }
}
